package com.jubotech.framework.netty.handler.websocket;

import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.google.protobuf.util.JsonFormat;
import com.jubotech.framework.netty.common.Constant;
import com.jubotech.framework.netty.utils.MessageUtil;

import Jubo.JuLiao.IM.Wx.Proto.DeviceAuthReq.DeviceAuthReqMessage;
import Jubo.JuLiao.IM.Wx.Proto.DeviceAuthReq.DeviceAuthReqMessage.EnumAuthType;
import Jubo.JuLiao.IM.Wx.Proto.TransportMessageOuterClass.EnumErrorCode;
import Jubo.JuLiao.IM.Wx.Proto.TransportMessageOuterClass.TransportMessage;
import io.netty.channel.ChannelHandlerContext;

@Service
public class DeviceAuthReqWebsocketHandler {
	private final Logger log = LoggerFactory.getLogger(getClass());
	  
	/**
	 * 设备校验 如果校验通过存储token、账号建立连接
	 * 
	 * @author wechatno:tangjinjinwx
	 * @param ctx
	 * @param vo
	 */
	@Async
	public void handleMsg(ChannelHandlerContext ctx, TransportMessage vo, String contentJsonStr) {
		try {
			log.debug(contentJsonStr);
			DeviceAuthReqMessage.Builder bd = DeviceAuthReqMessage.newBuilder();
			JsonFormat.parser().merge(contentJsonStr, bd);
			DeviceAuthReqMessage req = bd.build();
			if (null != req) {
				// 1、校验用户信息
				if (req.getAuthType().equals(EnumAuthType.Username)) {// 用户名密码方式（此方式Credential应传入base64(user:pwd)）
					byte[] byteArray = Base64.getDecoder().decode(req.getCredential());
					String str = new String(byteArray);
					System.out.println(str);
				} else {
					MessageUtil.sendJsonErrMsg(ctx, EnumErrorCode.NoRight, Constant.ERROR_MSG_VERIFYWAY);
				}
			} else {
				MessageUtil.sendJsonErrMsg(ctx, EnumErrorCode.InvalidParam, Constant.ERROR_MSG_DECODFAIL);
			}
		} catch (Exception e) {
			e.printStackTrace();
			MessageUtil.sendJsonErrMsg(ctx, EnumErrorCode.InvalidParam, Constant.ERROR_MSG_DECODFAIL);
		}

	}

	 

}